#!/bin/bash
# Describe: hongqi-balin-lms api install
# Date:        2022.08.19
# Author:      lcp
# Alter:       2022.08.19 V1.0
# 通过aws cli 判断最新api文件的时间是否更新
# 通过hostsname判断所在服务器及docker参数

#NEW_TAG=$1
#OLD_TAG=`echo "scale=1;$NEW_TAG-0.1"|bc|sed 's/^\./0&/'`
# =================================================================================================================================================

# version control
OLD_TAG=`/usr/bin/docker ps|awk -F '[ :]+' '/hongqi-lms-api/{print $3}'`
NEW_TAG=`echo "scale=1;${OLD_TAG}+0.1"|bc|sed 's/^\./0&/'`

# Time node
NEW_API_TIME=`aws s3 ls s3://hongqi-distribute-website/ops/hongqi-lms-api-0.0.1-SNAPSHOT.jar --profile lcp|awk -F '[ :|-]+' '{print $1$2$3$4$5}'`
OLD_API_TIME=`stat /home/centos/java/hongqi-lms-api-0.0.1-SNAPSHOT.jar|awk -F '[ :|-]+' '/Modify/{print $2$3$4$5$6}'`

# Hostname
HOSTNAME=`cat /etc/hostname`

# =================================================================================================================================================
api_wget() {
    /usr/bin/rm /home/centos/java/hongqi-lms-api-0.0.1-SNAPSHOT.jar
    cd /home/centos/java/
    wget https://hongqi-distribute-website.s3.me-south-1.amazonaws.com/ops/hongqi-lms-api-0.0.1-SNAPSHOT.jar
    echo `date` >> /data/scripts/api_install.log
    echo 'wget done' >> /data/scripts/api_install.log
}

docker_build_api() {
    cd /home/centos/java/
    /usr/bin/docker build . -t hongqi-lms-api:${NEW_TAG}
    echo `date` >> /data/scripts/api_install.log
    echo 'build done' >> /data/scripts/api_install.log
}


updata_bahrain_lms_api() {
    TGET=`echo ${HOSTNAME}|grep "south1-prod-bigdata-hadoop-node-03"|wc -l`
    if [ ${TGET} -eq "1" ];then
        /usr/bin/docker stop java-${OLD_TAG}
        /usr/bin/docker run -d --name=java-${NEW_TAG} -p 8080:8080/tcp --env JAVA_OPTS="-Dspring.profiles.active=production -Dwebsite.site-id=1 -Duser.timezone=Asia/Bahrain -Duser.language=en -Duser.region=BH -Xms4000m -Xmx4000m -XX:SurvivorRatio=1 -XX:MetaspaceSize=128M -XX:MaxMetaspaceSize=128M -Dlog4j2.formatMsgNoLookups=true" hongqi-lms-api:${NEW_TAG}
        echo `date` >> /data/scripts/api_install.log
        echo 'bahrain updata done' >> /data/scripts/api_install.log    
    else
        echo "此服务器-不是巴林LMS。。收到请回复,over"
    fi
}


# auto_updata_docker
if [ ${NEW_API_TIME}1 -eq ${OLD_API_TIME}1 ];then
    echo "=================`date`================WUXUGENGXIN========================================" >> /data/scripts/api_install.log  
    exit 1
else
    api_wget
    docker_build_api
    updata_bahrain_lms_api
    echo "================Updata version:==========${NEW_API_TIME}==================================" >>/data/scripts/api_install.log 
    exit 1
fi

